package com.itheima.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.itheima.domain.User;
import com.itheima.service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/*")
public class UsersServlet extends BaseServlet {
    // 查询所有的功能
    private void findAll(HttpServletRequest req , HttpServletResponse resp) throws IOException {
        //调用userService方法
        List<User> userList = userService.findAll();
        // 将list转化为json
        String json = obj.writeValueAsString(userList);
        resp.setContentType("text/json;charset=utf-8");
        //响应json数据
        resp.getWriter().write(json);
    }

    // 新增功能
    private void save(HttpServletRequest req , HttpServletResponse resp) throws IOException {
       // 获取新增的用户对象
        req.setCharacterEncoding("UTF-8");
        String USER = req.getParameter("userStr");
       // 将json字符串转化为对象
        User user = obj.readValue(USER, User.class);
       // 调用service方法将对象作为参数传入
       userService.save(user);
    }
    // 根据id删除指定的用户对象

    private void deleteByIds(HttpServletRequest req , HttpServletResponse resp) throws IOException {
        // 获取删除的id
        String ids = req.getParameter("ids");
        // 将字符串id转化为数组
        String[] ids1 = ids.split(",");
        Integer[] idsArray=new Integer[ids1.length];
        for (int i = 0; i < ids1.length; i++) {
            idsArray[i]=Integer.parseInt(ids1[i]);
        }
        // 调用方法把数组作为参数
        userService.deleteByIds(idsArray);
    }

    // 根据id查询更新用户信息
    // 新增功能
    private void update(HttpServletRequest req , HttpServletResponse resp) throws IOException {
        // 获取编辑后的用户对象
        req.setCharacterEncoding("UTF-8");
        String USER = req.getParameter("userStr");
        // 将json字符串转化为对象
        User user = obj.readValue(USER, User.class);
        // 调用service方法将对象作为参数传入
        userService.update(user);
    }









}
